# -*- coding: utf-8 -*-
"""
Created on  2022/8/3 12:01
@author: iris.wang
@file  : kgcore.py
"""

import requests, logging, datetime, time
import base.globalvars as glo
from base.get_config import get_header_file
from base.getdata import get_header
from util.db_util import execute_query
from jsonpath import jsonpath


def exc_xxl_job(job_id):
    """执行抽取xxl-job

    :param job_id: 任务id

    :return:无
    """
    try:
        job_url = glo.get_value("url11") + '/xxl-job-admin/jobinfo/trigger'
        start_time = (datetime.datetime.now()- datetime.timedelta(minutes=1)).strftime("%Y-%m-%dT%H:%M:%S")
        payload = {"id": job_id,
                   "executorParam": "master,--start_time=" + start_time}
        requests.post(job_url, data=payload, headers=get_header(get_header_file(), 'header4'))
        time.sleep(180)
    except Exception as e:
        logging.error("执行xxl-job抽取失败：%s" % e)
        return None

def validate_xxl_job(job_id):
    """检验job执行状态

        :param job_id: 任务id

        :return:bool
        """

    # 确认xxl_job执行成功并结束：通过调用调度列表接口查看该job状态为成功
    job_url = glo.get_value('url11') + '/xxl-job-admin/joblog/pageList'
    payload = {"jobId": job_id, "jobGroup": 1, "logStatus": -1, "length": 1}
    i = 0
    while i < 10:
        # 执行job等待3min后,每3s调用一次查询接口，10次查询仍未成功，认为超时
        res = requests.post(job_url, data=payload, headers=get_header(get_header_file(), 'header4'))
        if jsonpath(res.json(), "$.data[0].handleCode")[0] == 200:
            return True
        else:
            i += 1
            time.sleep(3)
    else:
        return False


def get_t_std_file_element(file_id, element_id):
    """获取kgcore文件元素表信息

        :param file_id: 文件id
        :param element_id: 元素id


        :return:文件元素表信息
        """
    sql = """SELECT * FROM `csf_kg_core`.`t_std_file_element` WHERE `file_id` = '%s' AND `element_id` = '%s'""" % (
        file_id, element_id)
    try:
        res = execute_query(sql, dbname="DB_kgcore", result_type="dict")
        return res
    except Exception as e:
        logging.error("get_t_std_file_element:%s" % e)
        return []

def get_t_std_file_element_detail(file_elem_id):
    """获取kgcore文件元素详情表信息

        :param file_elem_id: 文件元素表id

        :return:文件元素表信息
        """
    sql = """SELECT * FROM `csf_kg_core`.`t_std_file_element_detail` WHERE `file_elem_id` = '%s'""" % file_elem_id
    try:
        res = execute_query(sql, dbname='DB_kgcore', result_type='dict')
        return res
    except Exception as e:
        logging.error("get_t_std_file_element_detail:%s" % e)
        return []

def get_t_rpt_data_period(company_id, fiscal_yp):
    """获取报告期信息表

        :param company_id: org_id
        :param fiscal_yp: 报告期


        :return:报告期信息
        """
    sql = """SELECT * FROM `csf_kg_core`.`t_rpt_data_period` WHERE `company_id` = '%s' AND `fiscal_yp` = '%s' """ % (
        company_id, fiscal_yp)
    try:
        res = execute_query(sql, dbname="DB_kgcore", result_type="dict")
        return res
    except Exception as e:
        logging.error("get_t_rpt_data_period:%s" % e)
        return []


def get_t_sam_data(file_id,element_id,**kwargs):
    """获取kgcore抽取的sam数据信息

            :param file_id: 文件id
            :param element_id: 元素id


            :return:sam数据
            """
    condition="ORDER BY `id` DESC "
    if 'period_id' in kwargs:
        condition = "AND `period_id` = %s ORDER BY `id` DESC " %kwargs['period_id']
    elif 'std_product_code' in kwargs:
        condition = "AND `std_product_code`='%s' ORDER BY `id` DESC "%kwargs['std_product_code']
    else:
        logging.error("get_t_sam_data: period_id or std_product_code required!")

    sql = """SELECT * FROM `t_sam_data` 
        WHERE `file_elem_id` = (SELECT id FROM `csf_kg_core`.`t_std_file_element`  WHERE `file_id` = %s and `element_id`=%s )""" % (file_id,element_id) +condition

    try:
        res = execute_query(sql, dbname="DB_kgcore", result_type="dict")
        return res
    except Exception as e:
        logging.error("get_t_sam_data:%s" % e)
        return []

def get_t_std_rpt_period(file_id):
    """获取文件报告期信息表

        :param file_id: 文件id


        :return:报告期信息
        """
    sql = """SELECT * FROM `csf_kg_core`.`t_std_rpt_period` WHERE `file_id` = '%s' """ % (
        file_id)
    try:
        res = execute_query(sql, dbname="DB_kgcore", result_type="dict")
        return res
    except Exception as e:
        logging.error("get_t_std_rpt_period:%s" % e)
        return []

def get_t_std_period_element(file_id,element_id):
    """获取文件报告期元素表信息

        :param file_id: 文件id
        :param element_id: 元素id


        :return:文件报告期元素表信息
        """
    sql = """SELECT * FROM `csf_kg_core`.`t_std_period_element`  WHERE `file_id` = '%s' AND `element_id` = '%s'""" % (
        file_id,element_id)
    try:
        res = execute_query(sql, dbname="DB_kgcore", result_type="dict")
        return res
    except Exception as e:
        logging.error("get_t_std_period_element:%s" % e)
        return []

def get_t_config_biz(biz_code):
    """获取业务配置信息

        :param biz_code: das业务编码


        :return:kgcore中业务配置信息
        """
    sql = """SELECT * FROM `csf_kg_core`.`t_config_biz` WHERE `src_biz_code` = '%s'""" % (
        biz_code)
    try:
        res = execute_query(sql, dbname="DB_kgcore", result_type="dict")
        return res
    except Exception as e:
        logging.error("get_t_std_rpt_period:%s" % e)
        return []
